<template>
  <div class="reports-page">
    <header class="header">
      <div class="header-left">
        <el-button type="text" @click="$router.back()"><el-icon><ArrowLeft /></el-icon></el-button>
        <h1>诊断报告</h1>
      </div>
    </header>
    
    <div class="content">
      <div class="filter-section" v-if="isDoctor">
        <el-input v-model="searchKeyword" placeholder="搜索患者姓名或ID" style="width: 300px; margin-right: 10px;"></el-input>
        <el-button type="primary" @click="fetchReports">查询</el-button>
      </div>
      
      <el-card class="reports-list">
        <template #header>
          <div class="card-header">
            <span>{{ isDoctor ? '全部报告列表' : '我的诊断报告' }}</span>
          </div>
        </template>
        
        <el-table :data="filteredReports" style="width: 100%">
          <el-table-column prop="id" label="报告ID" width="100"></el-table-column>
          <el-table-column prop="patientId" label="患者ID" width="120" v-if="isDoctor"></el-table-column>
          <el-table-column prop="patientName" label="患者姓名" width="120"></el-table-column>
          <el-table-column prop="analysisResult" label="诊断结果" width="120">
            <template #default="scope">
              <el-tag :type="scope.row.analysisResult === '正常' ? 'success' : 'danger'">
                {{ scope.row.analysisResult }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="reviewStatus" label="复核状态" width="120" v-if="isDoctor">
            <template #default="scope">
              <el-tag :type="scope.row.reviewStatus === '已复核' ? 'success' : 'warning'">
                {{ scope.row.reviewStatus }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="analysisTime" label="分析时间" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.analysisTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="viewReport(scope.row)">
                查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      
      <!-- 报告详情对话框 -->
      <el-dialog
        v-model="dialogVisible"
        title="诊断报告详情"
        width="800px"
        :before-close="handleClose"
      >
        <div v-if="selectedReport" class="report-detail">
          <div class="report-header">
            <div class="patient-info">
              <h3>患者信息</h3>
              <p><strong>姓名：</strong>{{ selectedReport.patientName }}</p>
              <p><strong>ID：</strong>{{ selectedReport.patientId }}</p>
            </div>
            <div class="report-info">
              <h3>报告信息</h3>
              <p><strong>报告ID：</strong>{{ selectedReport.id }}</p>
              <p><strong>分析时间：</strong>{{ formatDate(selectedReport.analysisTime) }}</p>
              <p v-if="selectedReport.reviewStatus"><strong>复核状态：</strong>
                <el-tag :type="selectedReport.reviewStatus === '已复核' ? 'success' : 'warning'">
                  {{ selectedReport.reviewStatus }}
                </el-tag>
              </p>
            </div>
          </div>
          
          <div class="image-section">
            <h3>影像预览</h3>
            <div class="image-container" @click="enlargeImage(selectedReport)">
              <img :src="imagingStore.getImageUrl(selectedReport.imageFilename)" alt="医学影像" class="medical-image">
              <div class="image-overlay">
                <span class="zoom-hint">点击查看大图</span>
              </div>
            </div>
          </div>
          
          <div class="analysis-section">
            <h3>AI分析结果</h3>
            <div class="analysis-result">
              <div class="result-item">
                <span class="label">诊断结果：</span>
                <el-tag :type="selectedReport.analysisResult === '正常' ? 'success' : 'danger'" class="result-tag">
                  {{ selectedReport.analysisResult }}
                </el-tag>
              </div>
              <div class="result-item">
                <span class="label">置信度：</span>
                <el-progress :percentage="selectedReport.confidence * 100" status="success" class="confidence-bar"></el-progress>
                <span class="confidence-text">{{ (selectedReport.confidence * 100).toFixed(1) }}%</span>
              </div>
              <div class="result-item">
                <span class="label">分析详情：</span>
                <p class="details-text">{{ selectedReport.details }}</p>
              </div>
            </div>
            
            <!-- 医生复核信息 -->
            <h3>医生复核</h3>
            <div class="review-section">
              <div class="result-item">
                <span class="label">复核状态：</span>
                <el-tag :type="selectedReport.reviewStatus === '已复核' ? 'success' : 'warning'">
                  {{ selectedReport.reviewStatus || '待复核' }}
                </el-tag>
              </div>
              <div v-if="selectedReport.reviewStatus === '已复核'" class="result-item">
                <span class="label">复核时间：</span>
                <span class="confidence-text">{{ formatDate(selectedReport.reviewTime) }}</span>
              </div>
              <div v-if="selectedReport.reviewStatus === '已复核'" class="result-item">
                <span class="label">医生意见：</span>
                <div class="doctor-comment">
                  <p>{{ selectedReport.doctorComment || '无' }}</p>
                </div>
              </div>
            </div>
            
            <!-- 最终诊断报告（仅在报告生成后显示） -->
            <h3 v-if="selectedReport.reportGenerated && selectedReport.finalReport">最终诊断报告</h3>
            <div v-if="selectedReport.reportGenerated && selectedReport.finalReport" class="final-report-section">
              <div class="result-item">
                <span class="label">报告生成时间：</span>
                <span class="confidence-text">{{ formatDate(selectedReport.finalReport.generatedTime) }}</span>
              </div>
              <div class="result-item">
                <span class="label">报告状态：</span>
                <el-tag type="success">{{ selectedReport.finalReport.status }}</el-tag>
              </div>
              <div class="result-item">
                <span class="label">报告内容：</span>
                <div class="doctor-comment">
                  <p>{{ selectedReport.finalReport.content }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
        <template #footer>
          <el-button @click="handleClose">关闭</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '../stores/user';
import { useImagingStore } from '../stores/imaging';
import { ArrowLeft } from '@element-plus/icons-vue';

export default {
  name: 'Reports',
  components: {
    ArrowLeft
  },
  setup() {
    const router = useRouter();
    const userStore = useUserStore();
    const imagingStore = useImagingStore();
    const searchKeyword = ref('');
    const dialogVisible = ref(false);
    const selectedReport = ref(null);
    const reports = ref([]);
    
    // 模拟报告数据
    const mockReports = [
      { 
        id: 1, 
        patientId: 1, 
        patientName: '张三', 
        imageFilename: 'image-1728345678901.jpg', 
        analysisResult: '肺炎', 
        confidence: 0.92, 
        details: '右下肺叶可见浸润性阴影，考虑为肺炎', 
        analysisTime: '2024-10-01T10:30:00Z',
        reviewStatus: '已复核',
        doctorComment: '同意AI诊断，建议抗生素治疗',
        reviewTime: '2024-10-01T11:30:00Z',
        reportGenerated: true,
        finalReport: {
          id: 'R-20241001113000',
          generatedTime: '2024-10-01T11:30:00Z',
          content: '基于AI分析和医生复核，患者的诊断结果为：肺炎。医生意见：同意AI诊断，建议抗生素治疗',
          status: '已完成'
        }
      },
      { 
        id: 2, 
        patientId: 2, 
        patientName: '李四', 
        imageFilename: 'image-1728345678902.jpg', 
        analysisResult: '正常', 
        confidence: 0.97, 
        details: '胸部CT未见明显异常', 
        analysisTime: '2024-10-01T14:20:00Z',
        reviewStatus: '待复核',
        reportGenerated: false,
        finalReport: null
      },
      { 
        id: 3, 
        patientId: 3, 
        patientName: '王五', 
        imageFilename: 'image-1728345678903.jpg', 
        analysisResult: '可疑结节', 
        confidence: 0.85, 
        details: '右上肺叶可见小结节影，建议随访', 
        analysisTime: '2024-10-01T15:45:00Z',
        reviewStatus: '已复核',
        doctorComment: '结节较小，建议3个月后复查CT',
        reviewTime: '2024-10-01T16:30:00Z',
        reportGenerated: true,
        finalReport: {
          id: 'R-20241001163000',
          generatedTime: '2024-10-01T16:30:00Z',
          content: '基于AI分析和医生复核，患者的诊断结果为：可疑结节。医生意见：结节较小，建议3个月后复查CT',
          status: '已完成'
        }
      }
    ];
    
    const isDoctor = computed(() => userStore.userRole === 'doctor');
    
    onMounted(async () => {
      await fetchReports();
    });
    
    const fetchReports = async () => {
      try {
        let apiReports;
        if (isDoctor.value) {
          apiReports = await imagingStore.fetchAiReports();
        } else {
          // 患者只能查看自己的报告
          apiReports = await imagingStore.fetchAiReports(userStore.currentUser?.patientId);
        }
        
        // 直接使用API返回的数据，即使为空
        reports.value = Array.isArray(apiReports) ? apiReports : [];
      } catch (error) {
        console.error('加载诊断报告失败:', error);
        // 发生错误时保持列表为空
        reports.value = [];
      }
    };
    
    const filteredReports = computed(() => {
      // 过滤出只有已复核的报告
      const reviewedReports = reports.value.filter(report => report.reviewStatus === '已复核');
      
      if (!searchKeyword.value) return reviewedReports;
      
      const keyword = searchKeyword.value.toLowerCase();
      return reviewedReports.filter(report => 
        report.patientName.toLowerCase().includes(keyword) || 
        report.patientId.toString().includes(keyword) ||
        report.id.toString().includes(keyword)
      );
    });
    
    const viewReport = (report) => {
      selectedReport.value = report;
      dialogVisible.value = true;
    };
    
    const handleClose = () => {
      dialogVisible.value = false;
      selectedReport.value = null;
    };
    
    const enlargeImage = (report) => {
      // 创建全屏查看弹窗
      const overlay = document.createElement('div');
      overlay.className = 'image-overlay-fullscreen';
      overlay.innerHTML = `
        <div class="image-fullscreen-container">
          <img src="${imagingStore.getImageUrl(report.imageFilename)}" alt="医学影像大图" class="image-fullscreen">
          <button class="close-button">×</button>
          <div class="image-info">患者：${report.patientName} | 影像类型：${report.imageFilename}</div>
        </div>
      `;
      document.body.appendChild(overlay);
      
      // 添加关闭事件
      const closeButton = overlay.querySelector('.close-button');
      closeButton.addEventListener('click', () => {
        document.body.removeChild(overlay);
      });
      
      // 点击空白处关闭
      overlay.addEventListener('click', (e) => {
        if (e.target === overlay) {
          document.body.removeChild(overlay);
        }
      });
    };
    
    const formatDate = (dateString) => {
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    };
    
    return {
      isDoctor,
      searchKeyword,
      reports,
      filteredReports,
      dialogVisible,
      selectedReport,
      userStore,
      imagingStore,
      fetchReports,
      viewReport,
      handleClose,
      formatDate
    };
  }
};
</script>

<style scoped>
.reports-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  align-items: center;
  padding: 0 30px;
  height: 60px;
  background-color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header h1 {
  margin: 0;
  color: #303133;
  font-size: 20px;
}

.content {
  flex: 1;
  padding: 30px;
  background-color: #f5f7fa;
  overflow-y: auto;
}

.filter-section {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.reports-list {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.report-detail {
  padding: 20px 0;
}

.report-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.patient-info, .report-info {
  flex: 1;
}

.patient-info h3, .report-info h3, .image-section h3, .analysis-section h3 {
  margin: 0 0 15px 0;
  color: #303133;
}

.patient-info p, .report-info p {
  margin: 8px 0;
  color: #606266;
}

.image-section {
  margin-bottom: 30px;
}

.medical-image {
  max-width: 100%;
  max-height: 400px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.medical-image:hover {
  transform: scale(1.01);
}

.image-container {
  position: relative;
  display: inline-block;
}

.image-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  text-align: center;
  padding: 8px;
  border-radius: 0 0 4px 4px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.image-container:hover .image-overlay {
  opacity: 1;
}

.zoom-hint {
  font-size: 14px;
}

/* 全屏影像查看样式 */
.image-overlay-fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10000;
}

.image-fullscreen-container {
  position: relative;
  max-width: 90%;
  max-height: 90%;
  text-align: center;
}

.image-fullscreen {
  max-width: 100%;
  max-height: 80vh;
  border-radius: 4px;
}

.close-button {
  position: absolute;
  top: -40px;
  right: -20px;
  background: none;
  border: none;
  color: white;
  font-size: 40px;
  cursor: pointer;
  width: 40px;
  height: 40px;
  line-height: 40px;
  padding: 0;
  opacity: 0.7;
  transition: opacity 0.3s ease;
}

.close-button:hover {
  opacity: 1;
}

.image-info {
  color: white;
  margin-top: 15px;
  font-size: 14px;
}

.analysis-section {
  margin-bottom: 30px;
}

.analysis-result {
  background-color: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
}

.result-item {
  margin-bottom: 20px;
}

.label {
  font-weight: 500;
  color: #303133;
  margin-right: 10px;
}

.result-tag {
  font-size: 16px;
  padding: 5px 15px;
}

.confidence-bar {
  width: 200px;
  display: inline-block;
  vertical-align: middle;
  margin: 0 10px;
}

.confidence-text {
  color: #606266;
}

.details-text {
  margin: 10px 0 0 0;
  color: #606266;
  line-height: 1.8;
}

.doctor-comment {
  background-color: white;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  margin-top: 10px;
}

.doctor-comment p {
  margin: 0;
  color: #606266;
  line-height: 1.8;
}

@media (max-width: 768px) {
  .content {
    padding: 20px;
  }
  
  .header {
    padding: 0 20px;
  }
  
  .report-header {
    flex-direction: column;
    gap: 20px;
  }
  
  .confidence-bar {
    width: 100%;
    margin: 10px 0;
  }
}
</style>